package com.example.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.mapper.OrdersMapper;
import com.example.demo.pojo.BoardroomState;
import com.example.demo.mapper.BoardroomStateMapper;
import com.example.demo.pojo.Orders;
import com.example.demo.service.BoardroomStateService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author sjy
 * @since 2025-05-25
 */
@Service
public class BoardroomStateServiceImpl extends ServiceImpl<BoardroomStateMapper, BoardroomState> implements BoardroomStateService {

    @Autowired
    private BoardroomStateMapper boardroomStateMapper;

    @Autowired
    private OrdersMapper ordersMapper;

    @Override
    public IPage<BoardroomState> getBoardroomStatusList(Page<BoardroomState> page, Integer boardroomId, Date date, String startTime, String endTime, Integer state) {
        QueryWrapper<BoardroomState> queryWrapper = new QueryWrapper<>();

        // 添加会议室ID条件
        queryWrapper.eq("boardroom_id", boardroomId);

        // 添加日期条件
        if (date != null) {
            queryWrapper.eq("date", date);
        }

        // 添加开始时间条件
        if (startTime != null) {
            queryWrapper.ge("start_time", startTime);
        }

        // 添加结束时间条件
        if (endTime != null) {
            queryWrapper.le("end_time", endTime);
        }

        // 添加状态条件
        if (state != null) {
            queryWrapper.eq("state", state);
        }

        // 按日期和时间排序
        queryWrapper.orderByAsc("date", "start_time");

        return baseMapper.selectPage(page, queryWrapper);
    }

    @Transactional
    @Override
    public boolean updateBoardroomStatus(BoardroomState boardroomState) {
        Integer newState = boardroomState.getState();
        BoardroomState oldBoardroomState = boardroomStateMapper.selectById(boardroomState.getId());

        if(newState == 1){
            //如果是变成空闲，那么这条状态就会被删掉，订单状态变成已完成
            boolean updateOrdersState = updateOrdersState(oldBoardroomState);

            //删除状态
            if(updateOrdersState) {
                return judgeDeleteBoardroomState(oldBoardroomState.getId());
            }
        }else if(newState == 5){
            Integer oldState = oldBoardroomState.getState();
            Date newStartTime = oldBoardroomState.getEndTime();
            Date newEndTime = Date.from(newStartTime.toInstant().plus(Duration.ofMinutes(30)));
            if(oldState == 3 || oldState == 2){
                //如果是从预定/锁定变为维护
                newStartTime = oldBoardroomState.getStartTime();
                newEndTime = oldBoardroomState.getEndTime();
            }

            //如果是变成维护，那么这条状态就会被删掉，订单完成，然后新增往后半小时为维护状态
            boolean updateOrdersState = updateOrdersState(oldBoardroomState);

            //生成新的维护状态的状态
            if(updateOrdersState) {
                BoardroomState newBoardroomState = new BoardroomState();
                newBoardroomState.setBoardroomId(oldBoardroomState.getBoardroomId());
                newBoardroomState.setState(newState);
                newBoardroomState.setStartTime(newStartTime);
                newBoardroomState.setEndTime(newEndTime);
                newBoardroomState.setDate(oldBoardroomState.getDate());

                int insert = boardroomStateMapper.insert(newBoardroomState);

                if(insert > 0){
                    return judgeDeleteBoardroomState(boardroomState.getId());
                }
            }
        }else{
            //剩下的情况是预定->使用，或者锁定->使用，只用更新状态
            int updated = boardroomStateMapper.updateById(boardroomState);
            return updated > 0;
        }
        //在前面没有返回的就都是失败了
        return false;
    }

    private boolean judgeDeleteBoardroomState(int stateId) {
        int deleted = boardroomStateMapper.deleteById(stateId);
        return deleted > 0;
    }

    private boolean updateOrdersState(BoardroomState boardroomState) {
        QueryWrapper<Orders> ordersQueryWrapper = new QueryWrapper<>();
        ordersQueryWrapper.eq("boardroom_id", boardroomState.getBoardroomId());
        ordersQueryWrapper.eq("state_id", boardroomState.getId());
        Orders orders = ordersMapper.selectOne(ordersQueryWrapper);
        if (orders != null) {
            UpdateWrapper<Orders> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("boardroom_id", boardroomState.getBoardroomId());
            updateWrapper.eq("state_id", boardroomState.getId());
            updateWrapper.set("state",5);
            int update = ordersMapper.update(orders, updateWrapper);
            return update > 0;
        }
        //说明这个状态没有对应订单，也就是说是维修状态变成空闲状态
        return true;
    }
}
